package packet1;

import java.util.ArrayList;
import java.util.List;

public class course2 {
    static List<Integer> list = new ArrayList<>();
    public static void main(String[] args) {
//        int[] re = findOrder(5, new int[][]{{1,4},{2,4},{3,1},{3,2}});
        int[] re = findOrder(1, new int[][]{});
        for (int i = 0; i < re.length; i++) {
            System.out.print(re[i] + " ");
        }
    }
    public static int[] findOrder(int numCourses, int[][] prerequisites) {
        List<List<Integer>> ad = new ArrayList<>();
        int[] flags = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            ad.add(new ArrayList<>());
        }
        for (int i = 0; i < prerequisites.length; i++) {
            ad.get(prerequisites[i][0]).add(prerequisites[i][1]);
        }
        for (int i = 0; i < numCourses; i++) {
            if(!dfs(ad,flags,i))
                return new int[]{};
        }
        int[] re = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            re[i] = list.get(i);
        }
        return re;

    }
    public static boolean dfs(List<List<Integer>> ad, int[] flags, int i)
    {
        if(flags[i] == 2)
        {
            return false;
        }
        if(flags[i] == 1)
        {
            if(!list.contains(i))
            {
                list.add(i);
            }
            return true;
        }
        flags[i] = 2;
        for(int p : ad.get(i))
        {
            if(!dfs(ad,flags,p))
                return false;
        }
        flags[i] = 1;
        if(!list.contains(i))
        {
            list.add(i);
        }
        return true;
    }
}
